package com.ucode.springboot.starter.security.filter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.ucode.springboot.starter.security.service.UcodeSecurityOperationService;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * JWT token 过滤器
 * 在这里解析token，拿到该用户角色，设置到springsecurity的上下文环境中，让springsecurity自动判断权限
 * 所有请求最先进入此过滤器，包括登录接口，而且在springsecurity的密码验证之前执行
 * @author: liliang
 * @date: 2019年12月20日 下午3:13:59
 */
@Component
public class UcodeAuthenticationTokenFilter extends OncePerRequestFilter {
    
    private static Log log = LogFactory.get(UcodeAuthenticationTokenFilter.class);
    
    @Autowired
    private UcodeSecurityOperationService securityOperationService;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        
        log.debug("进入JWT token过滤器,class->JwtAuthenticationTokenFilter");
        // 获取token, 并检查登录状态
        /**
         * 注意:这里如果要获取其他参数进行处理，比如记录操作日志之类的通过
         * request.getParameter()不能读取到如 application/json 等 post 请求数据
         * 需要把读取参数逻辑修改为到流中读取request.getInputStream()
         * 
         * String body = getBody(request);
         * JSONObject jsonObject = JSON.parseObject(body);
         * String username = jsonObject.getString("username");
         * String password = jsonObject.getString("password");
         */
        securityOperationService.checkAuthentication(request);
        chain.doFilter(request, response);
        
    }
    
    /**
     * 获取请求Body
     * @author liliang
     * @date 2019年12月20日
     * @param request
     * @return
     */
    public String getBody(final ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = cloneInputStream(request.getInputStream());
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            log.error(e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }
        return sb.toString();
    }
    
    /**
     * 复制输入流
     * @author liliang
     * @date 2019年12月20日
     * @param inputStream
     * @return
     */
    public InputStream cloneInputStream(ServletInputStream inputStream) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            byteArrayOutputStream.flush();
        } catch (IOException e) {
            log.error(e);
        }
        InputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        return byteArrayInputStream;
    }

}
